// src/views/ProjectManagement.vue - 课题管理页面
<template>
  <div class="project-management-container">
    <div class="page-header">
      <h2>课题管理</h2>
      <p>管理平台所有课题项目，包括查看详情、更新状态等操作</p>
    </div>

    <!-- 搜索筛选区域 -->
    <el-card class="filter-card">
      <el-form
        :inline="true"
        :model="searchForm"
        class="filter-form"
      >
        <el-form-item label="课题名称">
          <el-input
            v-model="searchForm.keyword"
            placeholder="请输入课题名称"
            class="search-input"
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            class="filter-select"
          >
            <el-option label="全部" value="" />
            <el-option label="开放" value="open" />
            <el-option label="进行中" value="in_progress" />
            <el-option label="已完成" value="completed" />
            <el-option label="已关闭" value="closed" />
          </el-select>
        </el-form-item>

        <el-form-item label="分类">
          <el-select
            v-model="searchForm.category"
            placeholder="请选择分类"
            class="filter-select"
          >
            <el-option label="全部" value="" />
            <el-option label="人工智能" value="人工智能" />
            <el-option label="新材料" value="新材料" />
            <el-option label="网络安全" value="网络安全" />
            <el-option label="生物医药" value="生物医药" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 课题列表 -->
    <el-card class="table-card">
      <div class="table-container">
        <el-table
          v-loading="loading"
          :data="projectList"
          border
          stripe
          :header-cell-style="{ 'background-color': '#f5f7fa', 'font-weight': '500' }"
          class="project-table"
        >
          <el-table-column type="index" label="序号" width="80" align="center" />
          <el-table-column prop="title" label="课题名称">
            <template #default="{ row }">
              <div class="project-title">{{ row?.title || '未命名课题' }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="category" label="分类" min-width="100" />
          <el-table-column prop="budget" label="预算(元)" min-width="100" align="right">
            <template #default="{ row }">
              {{ row.budget.toLocaleString() }}
            </template>
          </el-table-column>

          <el-table-column label="标签" min-width="120">
            <template #default="{ row }">
              <div class="tag-group">
                <template v-if="row.tags && row.tags.trim()">
                  <el-tag
                    v-for="(tag, index) in row.tags.split(',')" 
                    :key="index"  
                    size="small"
                    type="info"
                  >
                    {{ tag.trim() }} 
                  </el-tag>
                </template>
                <span v-else class="no-tag">无标签</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column prop="status" label="状态" min-width="100">
            <template #default="scope">
              <el-tag
                :type="statusTypeMap[scope.row.status]?.type"  
                size="small"
              >
                {{ statusTypeMap[scope.row.status]?.label || '未知状态' }}
              </el-tag>
            </template>
          </el-table-column>

          <el-table-column prop="created_at" label="创建时间" min-width="160">
            <template #default="scope">
              {{ formatDate(scope.row.created_at) }}
            </template>
          </el-table-column>

          <el-table-column label="操作" min-width="160" fixed="right">
            <template #default="scope">
              <el-button
                size="small"
                type="text"
                @click="handleView(scope.row)"
                class="operation-btn"
              >
                查看
              </el-button>

              <el-select
                v-model="scope.row.newStatus"
                size="small"
                placeholder="更新状态"
                @change="(val:ProjectStatus) => handleStatusChange(scope.row, val)"
                class="status-select"
              >
                <el-option
                  v-for="item in getAvailableStatus(scope.row.status)"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { projectApi } from '@/api/admin';
import type { Project } from '@/api/adminTypes';
// 修改状态类型和映射
type ProjectStatus = 'open' | 'in_progress' | 'completed' | 'closed';

const statusTypeMap: Record<ProjectStatus, { label: string; type: string }> = {
  open: { label: '开放', type: 'success' },
  in_progress: { label: '进行中', type: 'primary' },
  completed: { label: '已完成', type: 'info' },
  closed: { label: '已关闭', type: 'danger' }
};

// 状态流转规则
const statusFlowRules: Record<ProjectStatus, ProjectStatus[]> = {
  'open': ['in_progress', 'closed'],
  'in_progress': ['completed', 'closed'],
  'completed': ['closed', 'open'],
  'closed': ['open']
};

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  category: ''
});

// 分页信息
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
});

// 表格数据
const projectList = ref<Project[]>([]);
const loading = ref(false);
const statusLoading = ref<number | null>(null);

// 获取课题列表
const getProjects = async () => {
  try {
    loading.value = true;

    // 构建请求参数
    const params = {
      page: pagination.page,
      size: pagination.size,
      status: searchForm.status || undefined,
      keyword: searchForm.keyword || undefined,
      category: searchForm.category || undefined
    };

    const res = await projectApi.getProjects(params);
    projectList.value = res.data.map((project: Project) => ({
      ...project,
      newStatus: project.status // 用于状态选择器的双向绑定
    }));
    pagination.total = res.data.total || 0;
  } catch (error) {
    console.error('获取课题列表失败:', error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  pagination.page = 1; // 重置到第一页
  getProjects();
};

// 重置表单
const resetForm = () => {
  searchForm.keyword = '';
  searchForm.status = '';
  searchForm.category = '';
  pagination.page = 1;
  getProjects();
};

// 查看课题详情
const handleView = (row: Project) => {
  // 这里可以跳转到课题详情页或打开详情弹窗
  console.log('查看课题:', row);
  ElMessage.info('课题详情功能待实现');
};

// 获取可用状态选项
const getAvailableStatus = computed(() => (currentStatus: string) => {
  const availableStatusValues = statusFlowRules[currentStatus as keyof typeof statusFlowRules] || [];

  return availableStatusValues.map(value => ({
    value,
    label: statusTypeMap[value as keyof typeof statusTypeMap]?.label || value
  }));
});

// 更新课题状态
// 修改状态变更方法
const handleStatusChange = async (row: Project, newStatus: ProjectStatus) => {
  try {
    loading.value = true;
    await projectApi.updateProjectStatus(row.id, newStatus);
    ElMessage.success('状态更新成功');
    getProjects();
  } catch (error) {
    console.error('更新状态失败:', error);
    ElMessage.error('状态更新失败');
  } finally {
    loading.value = false;
  }
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size;
  getProjects();
};

// 当前页码变化
const handleCurrentChange = (page: number) => {
  pagination.page = page;
  getProjects();
};

// 定义时间格式化函数，明确参数和返回值类型
const formatDate = (dateString: string | undefined | null): string => {
  // 处理空值或undefined
  if (!dateString) return '';
  
  try {
    const date = new Date(dateString);
    
    // 验证日期是否有效
    if (isNaN(date.getTime())) {
      return '无效时间';
    }
    
    // 获取年月日时分，并确保两位数格式
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  } catch (error) {
    console.error('时间格式化失败:', error);
    return '格式化错误';
  }
};

// 如果需要，可以定义表格行数据的类型接口（根据实际数据结构调整）
interface TableRow {
  CreatedAt: string;
  // 其他字段...
  // id: number;
  // name: string;
}

// 初始化页面加载数据
getProjects();
</script>

<style scoped lang="scss">
.project-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 60px);
}

.page-header {
  margin-bottom: 20px;

  h2 {
    margin-bottom: 5px;
    color: #1f2937;
  }

  p {
    color: #6b7280;
    font-size: 14px;
  }
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
}

.filter-form {
  padding: 15px 0;

  .search-input {
    width: 240px;
  }

  .filter-select {
    width: 140px;
  }
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
  overflow: hidden;
}

.table-container {
  overflow-x: auto;
}

.project-table {
  width: 100%;

  .project-title {
    font-weight: 500;
    color: #1f2937;
    transition: color 0.2s;

    &:hover {
      color: #409eff;
      cursor: pointer;
    }
  }

  .tag-group {
    display: flex;
    flex-wrap: wrap;
    gap: 4px;
  }

  .operation-btn {
    margin: 0 5px;
  }

  .status-select {
    width: 90px;
  }
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}

@media (max-width: 768px) {
  .filter-form {
    .el-form-item {
      margin-bottom: 10px;
      width: 100%;
    }

    .search-input, .filter-select {
      width: 100%;
    }
  }
}
</style>
